#!/usr/bin/perl
# by jzhang533@gmail.com at 2006-10-3
package jzhang::Log;
#-- Required Modules
#-------------------
use Symbol;
use strict;
use warnings;

# Constructor new
sub new {
    my $proto  = shift;
    my $class  = ref($proto) || $proto;

    my $self = {};
    bless($self, $class);

    # Run initialisation code
    return $self->_init(@_);
}

sub _init {
    my $self = shift;
    # Set some initial default values
    $self->{'logfilename'}     = 'log.txt';
    $self->{'logfilemode'}     = '>>';
    $self->{'datetimestamp'}   = 1;
    $self->{'_logFileOpen'}    = 0;
    $self->{'_fileHandle'}     = gensym;

    # Have we been passed anything
    if (@_ != 0) { # We are expecting our configuration to come as an anonymous hash
        if (ref $_[0] eq 'HASH') {
            my $hash=$_[0];
            foreach my $key (keys %$hash) {
                $self->{lc($key)}=$hash->{$key};
            }
        }else { # Using a more conventional named args
            my %args = @_;
            foreach my $key (keys %args) {
                $self->{lc($key)}=$args{$key};
            }
        }
    }
    # Open the logfile
    return $self->_open;
}

sub _open {
    my $self = shift;
    # If the current log file is open close it.
    close($self->{'_fileHandle'}) if($self->{'_logFileOpen'});
    # Actually open the log file
    unless (open($self->{'_fileHandle'}, $self->{'logfilemode'}.$self->{'logfilename'})) {
        $self->{'_logFileOpen'} = 0;
        return undef;
    }
    # Set the internal flag to indicate that the file is open
    $self->{'_logFileOpen'} = 1;
    local *LF = $self->{'_fileHandle'};
    # Set autoflush
    my $oldSelect = select LF;
    $| = 1;
    select $oldSelect;
    # Make the log file readable by all, modifiable by the owner
    # chmod 0644, $self->{'logfilename'};
    return $self;
}

sub msg {
    my $self = shift;
    my $now = '';
    my $str = join('', @_);
    # Set the timestamp if required
    $now = scalar(localtime()).'   ' if ($self->{'datetimestamp'});
    # Format the string and print it to the logfile
    $str =~ s/\n(?=.)/\n$now/gs;
    print {$self->{'_fileHandle'}} "$now".$str;
}

sub close {
    my $self = shift;
    close *{$self->{'_fileHandle'}} if (ref($self->{'_fileHandle'}) eq 'GLOB' && $self->{'_logFileOpen'});
    $self->{'_logFileOpen'} = 0;
}

sub dateTimeStamp {
    my $self = shift;
    my $prev = $self->{'datetimestamp'};
    if (@_) {
        $self->{'datetimestamp'} = ($_[0] ? 1: 0);
    }
     return $prev;
}

sub getLogFileName { return $_[0]->{'logfilename'}; }

1;
